package com.zhang.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.zhang.entity.User;
import com.zhang.service.UserService;
import com.zhang.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//连接数据库获取认证信息
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    UserService userService;

    //判断token是否为JwtToken的类型，方便doGetAuthenticationInfo()中强转
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //JwtFilter之后会进入此方法，获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        JwtToken jwtToken = (JwtToken)token;
        Claims claim = jwtUtil.getClaimByToken((String) jwtToken.getPrincipal());
        String userId = claim.getSubject();
        User user = userService.getById(Long.valueOf(userId));
        if(user == null){
            throw new UnknownAccountException("用户不存在");
        }
        if(user.getStatus() == -1){
            throw new LockedAccountException("用户已被禁用");
        }

        AccountProfile profile = new AccountProfile();  //用于返回给shiro，用户的基本信息
        BeanUtil.copyProperties(user,profile);

        return new SimpleAuthenticationInfo(profile,jwtToken.getCredentials(),getName());
    }
}
